from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import os

# 如果您尚未安装openai SDK，请先运行: pip install openai
from openai import OpenAI

@csrf_exempt
def chat_with_ai(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_message = data.get('message')
            conversation_history = data.get('history', [])

            if not user_message:
                return JsonResponse({'error': 'Missing message'}, status=400)

            # 获取DeepSeek API Key (建议通过环境变量管理)
            DEEPSEEK_API_KEY = "sk-5845b7996ad44f08a43a9d820bfbe211"  # 直接赋值您的API Key


            try:
                client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")
                messages = [{"role": "system", "content": "You are an AI assistant for a library, specifically designed to act as a famous author from history. Respond in the persona of a historical author, making the conversation engaging and informative, as if you are discussing books and literature across time. Keep responses concise and focused on the literary aspect."}]
                for msg in conversation_history:
                    messages.append(msg)
                messages.append({"role": "user", "content": user_message})

                response = client.chat.completions.create(
                    model="deepseek-chat", # 或 deepseek-reasoner，取决于您的需求
                    messages=messages,
                    stream=False
                )
                ai_response = response.choices[0].message.content
            except Exception as e:
                return JsonResponse({'error': f'Failed to communicate with DeepSeek API: {str(e)}'}, status=500)

            return JsonResponse({'reply': ai_response})
        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON'}, status=400)
    return JsonResponse({'error': 'Invalid request method'}, status=405)

@csrf_exempt
def get_book_summary(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            book_title = data.get('book_title')

            if not book_title:
                return JsonResponse({'error': 'Missing book title'}, status=400)

            # 获取DeepSeek API Key (建议通过环境变量管理)
            DEEPSEEK_API_KEY = "sk-5845b7996ad44f08a43a9d820bfbe211"  # 直接赋值您的API Key


            try:
                client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")
                messages = [
                    {"role": "system", "content": "You are a helpful assistant. Provide a concise summary of the requested book, focusing on its main plot, themes, and significance."},
                    {"role": "user", "content": f"请为我总结一下书籍：{book_title}"}
                ]

                response = client.chat.completions.create(
                    model="deepseek-chat", # 或 deepseek-reasoner，取决于您的需求
                    messages=messages,
                    stream=False
                )
                book_summary = response.choices[0].message.content
            except Exception as e:
                return JsonResponse({'error': f'Failed to communicate with DeepSeek API: {str(e)}'}, status=500)

            return JsonResponse({'summary': book_summary})
        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON'}, status=400)
    return JsonResponse({'error': 'Invalid request method'}, status=405) 